/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 所有图标数据，目前只归类大屏数据，后期需要将所有的图标数据整合
 *  */

import { message } from 'antd';
import { isLegalData, mergeObjectsByKeys, removeCookie } from '@/utils/utils';
import {
  getMapData,
  getRealTimeData,
  getYesterdayDate,
  getHasVideoCmId,
  getCityChannelList,
  playCityVideos,
  videoCityStart,
  videoCityStop,
  getAreaYzData,
  getYesterdayInNum,
  storageSummary,
  brandsRate,
  getSubDaksList,
  pdaSummary,
  getYzGpYesterdayDate,
  getYzGpYesterdayArrivalRank,
  getYzGpYesterdayBrandArrivalRank,
  getYzGpSevenRank,
  getYzGpArriveBrandRate,
  getYzGpArriveRealTimeDate,
  getYzGpAreaDate,
} from '../services/chartData';
import {
  getRealTimeChart,
  getInStorageNum,
  getOutStorageNum,
  getOutRate,
  getOutRateRange,
  getBrandRateRange,
  getStorageInNumRankYesterday,
  getTopRealTimeData,
} from '../services/dashboard';

export default {
  namespace: 'chartData',

  state: {
    currentAreaInfo: {
      currentUserLevel: [],
      branchId: null,
      currentName: null,
      currentLevel: null,
      cmId: null,
      code: null,
    },
    mapData: null,
    areaYzData: null,
    yesterdayDate: {},
    preHourOutNum: [],
    yesterdayInNum: [],
    cmidsWithVideo: [],
    channelList: [],
    liveId: '',
    yzTopRealData: [
      {
        key: 'in_num',
        title: '今日入库数',
      },
      {
        key: 'arrive_num',
        title: '今日到件扫描',
      },
      {
        key: 'send_num',
        title: '今日派件扫描',
      },
      {
        key: 'express_num',
        title: '今日寄件数',
      },
      {
        key: 'express_fee',
        title: '今日快递费',
      },
      {
        key: 'out_num',
        title: '今日出库数',
      },
    ],
    yzLegendsMap: {
      arrive_num: {
        label: '到件',
        color: '#ff756b',
      },
      send_num: {
        label: '派件',
        color: '#19c0b7',
      },
      in_num: {
        label: '入库',
        color: '#d8af30',
      },
      out_num: {
        label: '出库',
        color: '#3591e6',
      },
    },
    gpScanOrders: [],
    zyGpYesterdayDate: {},
  },

  effects: {
    *getMapData({ payload, __dva_resolve }, { call }) {
      const res = yield call(getMapData, payload);
      if (res) {
        __dva_resolve(res);
      }
    },
    // 更新当前地区层级
    *updateAreaInfo({ payload }, { put, select }) {
      const { currentAreaInfo = {} } = yield select(_ => _.chartData) || {};
      yield put({
        type: 'save',
        payload: {
          currentAreaInfo: {
            ...currentAreaInfo,
            ...payload,
          },
        },
      });
    },
    // 获取地图驿站数据
    *getAreaYzData({ payload, __dva_resolve }, { call, put }) {
      const res = yield call(getAreaYzData, payload);
      const { code, msg, data } = res || {};
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            areaYzData: isLegalData(data),
          },
        });
        __dva_resolve(isLegalData(data));
      } else {
        message.error(msg);
      }
    },
    // 获取实时看板数据
    *getRealTimeData({ payload = {}, __dva_resolve, __dva_reject }, { call }) {
      const res = yield call(getRealTimeData, payload);
      const { code, data, msg } = res || {};
      if (code == 0) {
        __dva_resolve(isLegalData(data, {}));
      } else {
        message.error(msg);
        __dva_reject();
      }
    },
    // 获取昨日数据看板
    *getYesterdayDate({ payload, __dva_resolve }, { call, put }) {
      const res = yield call(getYesterdayDate, payload);
      // const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            yesterdayDate: isLegalData(data, {}),
          },
        });
        __dva_resolve(isLegalData(data, {}));
      } else {
        // removeCookie(screenKey);
        message.error(msg);
      }
    },
    // 昨日入库数
    *getYesterdayInNum({ payload, __dva_resolve }, { call, put }) {
      const res = yield call(getYesterdayInNum, payload);
      // const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            yesterdayInNum: isLegalData(data),
          },
        });
        __dva_resolve(isLegalData(data));
      } else {
        // removeCookie(screenKey);
        message.error(msg);
      }
    },
    // 7日出入库数
    *storageSummary({ payload, __dva_resolve }, { call, put }) {
      const res = yield call(storageSummary, payload);
      // const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            inOutNumbers: isLegalData(data),
          },
        });
        __dva_resolve(isLegalData(data));
      } else {
        message.error(msg);
        // removeCookie(screenKey);
      }
    },
    // 近7日共配扫描数
    *pdaSummary({ payload, __dva_resolve }, { call, put }) {
      const res = yield call(pdaSummary, payload);
      const { code, data, msg } = res || {};
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            gpScanOrders: isLegalData(data),
          },
        });
        __dva_resolve(isLegalData(data));
      } else {
        message.error(msg);
      }
    },
    // 7日入库品牌占比
    *getBrandsRate({ payload, __dva_resolve }, { call, put }) {
      const res = yield call(brandsRate, payload);
      // const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            brandsRate: isLegalData(data),
          },
        });
        __dva_resolve(isLegalData(data));
      } else {
        message.error(msg);
        // removeCookie(screenKey);
      }
    },
    // 下属驿站
    *getSubDaksList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const res = yield call(getSubDaksList, payload);
      if (!res) return;
      const { code, data } = res;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            yzList: isLegalData(data, []),
          },
        });
        __dva_resolve(isLegalData(data, []));
      } else {
        __dva_reject(res);
      }
    },

    // 宇视-获取有设备的驿站id
    *getHasVideoCmId({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const res = yield call(getHasVideoCmId, payload);
      const { code, data, msg } = res || {};
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            cmidsWithVideo: isLegalData(data),
          },
        });
        __dva_resolve(data);
      } else {
        message.error(msg);
        __dva_reject(res);
      }
    },

    // 宇视-获取宇视通道号
    *getCityChannelList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const res = yield call(getCityChannelList, payload);
      const { code, data, msg } = res || {};
      const { channelList } = data;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            channelList: isLegalData(channelList),
          },
        });
        __dva_resolve(data);
      } else {
        if (code != 1000) {
          message.error(msg);
        }
        __dva_reject(res);
      }
    },
    // 宇视-获取视频地址
    *getVideoURL({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const res = yield call(playCityVideos, payload);
      const { code, data, msg } = res || {};
      const { hlsUrl } = data;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            videoURL: hlsUrl,
          },
        });
        __dva_resolve(hlsUrl);
      } else {
        message.error(msg);
        __dva_reject(res);
      }
    },
    // 宇视-开启推流
    *startLive({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const res = yield call(videoCityStart, payload);
      const { code, data, msg } = res || {};
      const { liveId } = data;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            liveId,
          },
        });
        __dva_resolve(liveId);
      } else {
        message.error(msg);
        __dva_reject(res);
      }
    },
    // 宇视-关闭推流
    *stopLive({ payload, __dva_resolve, __dva_reject }, { call }) {
      const res = yield call(videoCityStop, payload);
      const { code, data, msg } = res || {};
      const { liveId } = data;
      if (code == 0) {
        __dva_resolve(liveId);
      } else {
        message.error(msg);
        __dva_reject(res);
      }
    },
    // 新零售大屏，获取顶部实时数据
    *getTopRealTimeData({ payload, __dva_resolve, __dva_reject }, { call, select }) {
      const { yzTopRealData = {} } = yield select(_ => _.chartData) || {};
      const { screenKey } = yield select(_ => _.global) || {};
      const res = yield call(getTopRealTimeData, payload);
      const { code, data = {}, msg } = res || {};
      if (code == 0) {
        const list = [];
        Object.keys(isLegalData(data, {})).forEach(val => {
          yzTopRealData.forEach(({ title, key }) => {
            if (key === val) {
              list.push({
                ...data[key],
                title,
                key,
              });
            }
          });
        });
        __dva_resolve(list);
      } else {
        removeCookie(screenKey);
        __dva_reject(res);
        message.error(msg);
      }
    },
    // 新零售大屏，获取折线图实时数据
    *getRealTimeChart({ payload, __dva_resolve, __dva_reject }, { call, put, select }) {
      const res = yield call(getRealTimeChart, payload);
      const { screenKey } = yield select(_ => _.global) || {};
      const { yzLegendsMap } = yield select(_ => _.chartData);
      const { code, data, msg } = res || {};

      if (code == 0) {
        const list = isLegalData(data) || [];
        const first = data[0] || {};
        const keys = Object.keys(first);
        const obj = {};
        keys.forEach(key => {
          if (yzLegendsMap[key]) {
            obj[key] = yzLegendsMap[key];
          }
        });
        // 不显示最后一个数据，方便同步顶部实时数据
        list.splice(list.length - 1, 1);
        yield put({
          type: 'save',
          payload: {
            realTimeChartData: list,
            yzLegendsMap: obj,
          },
        });
        __dva_resolve(list);
      } else {
        removeCookie(screenKey);
        __dva_reject(res);
        message.error(msg);
      }
    },
    // 新零售大屏，每日入库量
    *getInStorageNum({ payload, __dva_resolve }, { call, select }) {
      const res = yield call(getInStorageNum, payload);
      const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};
      if (code != 0) {
        removeCookie(screenKey);
        message.error(msg);
      }
      __dva_resolve(isLegalData(data));
    },
    // 新零售大屏，每日寄件量
    *getOutStorageNum({ payload, __dva_resolve }, { call, select }) {
      const res = yield call(getOutStorageNum, payload);
      const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};
      if (code != 0) {
        removeCookie(screenKey);
        message.error(msg);
      }
      __dva_resolve(isLegalData(data));
    },
    // 新零售大屏，每日出库率
    *getOutRate({ payload, __dva_resolve }, { call, select }) {
      const res = yield call(getOutRate, payload);
      const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};

      if (code != 0) {
        message.error(msg);
        removeCookie(screenKey);
      }
      __dva_resolve(isLegalData(data));
    },
    // 新零售大屏，出库率(3日)排名
    *getOutRateRange({ payload, __dva_resolve }, { call, select }) {
      const res = yield call(getOutRateRange, payload);
      const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};

      if (code != 0) {
        message.error(msg);
        removeCookie(screenKey);
      }
      __dva_resolve(isLegalData(data));
    },
    // 新零售大屏，昨日入库品牌占比
    *getBrandRateRange({ payload, __dva_resolve }, { call, select }) {
      const res = yield call(getBrandRateRange, payload);
      const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};

      if (code != 0) {
        message.error(msg);
        removeCookie(screenKey);
      }
      __dva_resolve(isLegalData(data));
    },
    // 新零售大屏，昨日入库量排名
    *getStorageInNumRankYesterday({ payload, __dva_resolve }, { call, select }) {
      const res = yield call(getStorageInNumRankYesterday, payload);
      const { screenKey } = yield select(_ => _.global) || {};
      const { code, data, msg } = res || {};

      if (code != 0) {
        message.error(msg);
        removeCookie(screenKey);
      }
      __dva_resolve(isLegalData(data));
    },
    /**
     * 中邮共配大屏，获取驿站近7天数据
     *  */
    *getYzGpYesterdayDate({ payload, __dva_resolve }, { call, select }) {
      const { screenKey } = yield select(_ => _.global) || {};
      const { code: reqCode, level, token } = payload;
      const res = yield call(getYzGpYesterdayDate, {
        code: reqCode,
        level,
        token,
      });
      const yzData = yield call(getYesterdayDate, payload);
      const { code, data, msg } = res || {};
      const {
        data: { in_data = {} },
      } = yzData || {};
      if (code == 0) {
        __dva_resolve({ ...isLegalData(data, {}), in_data });
      } else {
        removeCookie(screenKey);
        message.error(msg);
      }
    },
    /**
     * 中邮共配大屏，获取昨日每小时到件量排名
     *  */
    *getYzGpYesterdayArrivalRank({ payload, __dva_resolve }, { call, select }) {
      const { code: reqCode, level, token } = payload;
      const { screenKey } = yield select(_ => _.global) || {};
      const res = yield call(getYzGpYesterdayArrivalRank, {
        code: reqCode,
        level,
        token,
      });
      const { code, data, msg } = res || {};
      if (code == 0) {
        __dva_resolve(isLegalData(data, []));
      } else {
        removeCookie(screenKey);
        message.error(msg);
      }
    },
    /**
     * 中邮共配大屏，获取昨日到件品牌排名
     *  */
    *getYzGpYesterdayBrandArrivalRank({ payload, __dva_resolve }, { call, select }) {
      const { code: reqCode, level, token } = payload;
      const { screenKey } = yield select(_ => _.global) || {};
      const res = yield call(getYzGpYesterdayBrandArrivalRank, {
        code: reqCode,
        level,
        token,
      });
      const { code, data, msg } = res || {};
      if (code == 0) {
        data.forEach(val => {
          val.brand = val.zh_cn;
        });
        __dva_resolve(isLegalData(data, []));
      } else {
        removeCookie(screenKey);
        message.error(msg);
      }
    },
    /**
     * 中邮共配大屏，获取近7日到件量
     *  */
    *getYzGpSevenRank({ payload, __dva_resolve }, { call }) {
      const { code: reqCode, level, token } = payload;
      const res = yield call(getYzGpSevenRank, {
        code: reqCode,
        level,
        token,
      });
      const { code, data, msg } = res || {};
      if (code == 0) {
        __dva_resolve(isLegalData(data, []));
      } else {
        message.error(msg);
      }
    },
    /**
     * 中邮共配大屏，获取近7日到件品牌占比
     *  */
    *getYzGpArriveBrandRate({ payload, __dva_resolve }, { call }) {
      const { code: reqCode, level, token } = payload;
      const res = yield call(getYzGpArriveBrandRate, {
        code: reqCode,
        level,
        token,
      });
      const { code, data = [], msg } = res || {};
      if (code == 0) {
        data.forEach(val => {
          val.num = val.sum_num;
          val.brand = val.zh_cn;
        });
        __dva_resolve(isLegalData(data));
      } else {
        message.error(msg);
      }
    },
    /**
     * 中邮共配大屏，获取今日实时数据
     *  */
    *getYzGpArriveRealTimeDate({ payload, __dva_resolve }, { call }) {
      const { code: reqCode, level, type, token } = payload;

      const res = yield call(getYzGpArriveRealTimeDate, {
        code: reqCode,
        level,
        token,
      });
      const { code, data = {}, msg } = res || {};
      const resDat = {
        total: data[type],
        yz_total: data[`ems_${type}`],
      };
      if (code == 0) {
        __dva_resolve(resDat);
      } else {
        message.error(msg);
      }
    },
    /**
     * 中邮共配大屏，获取地区热力图数据
     *  */
    *getYzGpAreaDate({ payload, __dva_resolve }, { call }) {
      const gpRes = yield call(getYzGpAreaDate, payload);
      const yzRes = yield call(getAreaYzData, payload);
      const { code, msg, data: gpData = [] } = gpRes || {};
      const { data: yzData = [] } = yzRes || {};
      if (code == 0) {
        const newArr = [...isLegalData(gpData), ...isLegalData(yzData)];
        newArr.forEach(v => {
          if (v.abbr_name) {
            v.areaName = v.abbr_name;
          }
        });
        const arr = mergeObjectsByKeys(newArr, ['areaName']);
        console.log('arr', arr);
        __dva_resolve(isLegalData(arr));
      } else {
        message.error(msg);
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
